#include "ServerMessageHandler.h"
#include "Controller.h"

#include <iostream>

using namespace resip;
using namespace std;

ServerMessageHandler::ServerMessageHandler(Controller* parent) : m_owner(parent)
{
	initialize();
}

ServerMessageHandler::~ServerMessageHandler()
{
	cleanup();
}

void ServerMessageHandler::initialize()
{
}

void ServerMessageHandler::cleanup()
{
}

// Callbacks: ServerPagerMessageHandle

void ServerMessageHandler::onMessageArrived(ServerPagerMessageHandle h, const SipMessage & message)
{
	// Get the contact

	const HeaderFieldValueList* from = message.getRawHeader(Headers::From);
	const HeaderFieldValue* value = from->front();
	string valueString = value->mField;

	string result = parseContactName(valueString.substr(0, value->mFieldLength));

	// Get the contents

	Contents* content = message.getContents();
	string contentString = content->getBodyData().c_str();

	// Show message

	m_owner->messageReceived(result, contentString);

	// Sent response

	SharedPtr<SipMessage> ok = h->accept();
	h->send(ok);

	cout << ">>SERVER: Message arrived" << endl;
}

string ServerMessageHandler::parseContactName(string from)
{
	char* buffer = 0;
	char* result = 0;

	buffer = new char[from.size() + 1];
	strcpy(buffer, from.c_str());

	// Filter user

	result = strtok(buffer, ":");
	result = strtok(NULL, "@");

	// Return result

	return string(result);
}